package com.flca.frw.components.wizzard
{
	import com.flca.frw.components.SimpleBaseCtrl;
	import com.flca.frw.events.EventBroker;
	
	import mx.containers.Panel;
	import mx.controls.Alert;
	
	public class GenericWizzardCtrl extends Panel
	{
		private var _wizzrdData : GenWzrdData;
		
		public function GenericWizzardCtrl()
		{
		}

		public function get view() : GenericWizzardView {
			return this as GenericWizzardView;
		}
		
		/**
		 * This will setup all the pages and steps control
		 * 
		 */
		public function setup(aWizzData: GenWzrdData) : void
		{
			_wizzrdData = aWizzData;
			
			if (_wizzrdData == null) {
				Alert.show("GenericWizzardCtrl.setup() error: Wizzard data or Handler is null");
				return;
			}
			
			view.title = _wizzrdData.title;
			
			view.steps.pages = _wizzrdData.pages;

			view.viewstack.removeAllChildren();
			for each (var page:GenWzrdPage in _wizzrdData.pages) {
				view.viewstack.addChild(page.view);
			}

			activatePage(0);
		}
		
		private function activatePage(aIndex:int) : void 
		{
			view.viewstack.selectedIndex = aIndex;
			EventBroker.instance.sendEvent(new ActivatePageEvent(0));		
			updateGuiState();

			var i:int = 0;
			for each (var page:GenWzrdPage in _wizzrdData.pages) {
				page.active = (i == aIndex);

				if (page.active) {
					view.title = page.title;
				}
				
				i++;
			}
		}
		
		private function get activePage() : SimpleBaseCtrl
		{
			var page:GenWzrdPage = _wizzrdData.pages.getItemAt(activeIndex) as GenWzrdPage;
			return page.view;
		}
		
		private function updateGuiState() : void
		{
			view.btnPrev.visible = (activeIndex > 0);
			view.btnPrev.includeInLayout = (activeIndex > 0);
			
			view.btnNext.visible = (!isLastIndex());
			view.btnNext.includeInLayout = (!isLastIndex());
			
			view.btnFinish.visible = (isLastIndex());
			view.btnFinish.includeInLayout = (isLastIndex());
		}
		
		private function get activeIndex() : int {
			return view.viewstack.selectedIndex;	
		}
		
		private function isLastIndex() : Boolean 
		{
			return (activeIndex >= view.viewstack.getChildren().length - 1);	
		}

		public function onCancel() : void
		{
			EventBroker.instance.sendEvent( new CloseWizzardEvent());
		}

		public function onPrev() : void
		{
			activatePage(activeIndex - 1);
		}


		public function onNext() : void
		{
			var page:SimpleBaseCtrl = activePage;
			if (page != null && page.validate()) {
				activatePage(activeIndex + 1);
			}
		}


		//override this !!
		public function onFinish() : void
		{
			Alert.show("OVERRIDE THIS METHOD");
		}
		
		public function get wizzrdData() : GenWzrdData {
			return _wizzrdData;
		}
		
		public function set wizzrdData(value:GenWzrdData) : void {
			_wizzrdData = value;
		}
		
	}
}